import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Dispatch } from 'redux';
import { message } from 'antd';
import { ColumnProps } from 'antd/lib/table';
import { ConnectState, ConnectProps, ManageDepartmentModelState } from '@/models/connect';
import { ModalStatus } from '@/constants/common';
import PageTable, { FilterItemProps, FilterOptionProps } from '@/components/PageTable';
import {
  IDepartmentListItem,
  IDepartmentListQueryParams,
  ICreateDepartmentParams,
  IDepartmentFilterOpts,
} from '@/services/manageDepartment';
import CommonModal from '@/components/Modal/CommonModal';
import { DepartmentFilterCfg, DepartmentStatusList } from './config/department';
import DepartmentModal from './DepartmentModal';
import styles from './ManageDepartment.less';

type OperaType = 'start' | 'disable' | 'delete';

interface ManageDepartmentComponentProps extends ConnectProps {
  createLoading: boolean;
  manageDepartment: ManageDepartmentModelState;
  getTableList: (params: object) => void;
  getFilters: () => void;
  createItem: () => Promise<any>;
  deleteItem: (id: number) => Promise<any>;
  updateItem: (params: Partial<ICreateDepartmentParams>) => Promise<any>;
}

const ManageDepartment: React.FC<ManageDepartmentComponentProps> = props => {
  const [modalStatus, setModalStatus] = useState(ModalStatus.Hide);
  const [itemInfo, setItemInfo] = useState<IDepartmentListItem>({});
  const [filterCfgList, setFilterCfgList] = useState(DepartmentFilterCfg);
  const [operaType, setOperaType] = useState<OperaType>('start');
  const [needRefresh, setNeedFresh] = useState(false);

  const {
    manageDepartment,
    getTableList,
    createItem,
    deleteItem,
    updateItem,
    getFilters,
    createLoading,
  } = props;
  const { total = 0, tableList = [], filterOpts = {} } = manageDepartment;

  useEffect(() => {
    getFilters();
  }, []);

  useEffect(() => {
    const newCfgList: Array<FilterItemProps> = [];
    const { type = [] } = filterOpts as IDepartmentFilterOpts;

    filterCfgList.map(item => {
      if (item.filter === 'type') {
        const typeOpts: Array<FilterOptionProps> = type.map(item => ({
          value: item,
          key: item,
        }));
        newCfgList.push({ ...item, options: typeOpts });
      } else {
        newCfgList.push({ ...item });
      }
    });

    setFilterCfgList(newCfgList);
  }, [filterOpts]);

  const hideModal = () => {
    setModalStatus(ModalStatus.Hide);
  };

  // 新增条目操作
  const createItemOpera = () => {
    setModalStatus(ModalStatus.Create);
    setItemInfo({});
  };

  // 编辑条目操作
  const eidtItemOpera = (record: IDepartmentListItem) => {
    setModalStatus(ModalStatus.Edit);
    setItemInfo(record);
  };

  // 删除条目操作
  const deleteItemOpera = () => {
    if (itemInfo.status !== 0) {
      message.error('请先禁用当前项目!');
      return;
    }

    setNeedFresh(false);

    deleteItem(itemInfo.id).then(() => {
      setModalStatus(ModalStatus.Hide);
      setNeedFresh(true);
    });
  };

  // 启用/禁用条目操作
  const updateItemOpera = (status: number) => {
    setNeedFresh(false);

    updateItem({ id: itemInfo.id, status }).then(() => {
      setModalStatus(ModalStatus.Hide);
      setNeedFresh(true);
    });
  };

  const handleAcitons = (type: OperaType, record: IDepartmentListItem) => {
    setModalStatus(ModalStatus.Delete);
    setOperaType(type);
    setItemInfo(record);
  };

  const MODAL_CFG = {
    start: {
      title: '启用',
      content: '您确认启用该项吗？',
      onOk: () => updateItemOpera(1),
    },
    disable: {
      title: '禁用',
      content: '您确认禁用该项吗？',
      onOk: () => updateItemOpera(0),
    },
    delete: {
      title: '删除',
      content: '您确认删除该项吗？',
      onOk: deleteItemOpera,
    },
  };

  const columns: Array<ColumnProps<IDepartmentListItem>> = [
    {
      title: '项目名称',
      key: 'name',
      width: 120,
    },
    {
      title: '项目类型',
      key: 'type',
      width: 130,
    },
    {
      title: '关联平台',
      key: 'platform',
      width: 140,
    },
    {
      title: '项目标签',
      key: 'tags',
      width: 80,
      render: text => text && text.join(','),
    },
    {
      title: '项目状态',
      key: 'status',
      width: 90,
      render: text => {
        const item = DepartmentStatusList[text];

        if (item) {
          return (
            <span
              className={styles.pageTag}
              style={{ backgroundColor: `${item.bg}`, color: `${item.color}` }}
            >
              {item.name}
            </span>
          );
        } else {
          return null;
        }
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 154,
      render: (text, record) => (
        <div className={styles.pageTableAction}>
          {record.status === 0 ? (
            <a onClick={() => handleAcitons('start', record)}>启用</a>
          ) : (
            <a onClick={() => handleAcitons('disable', record)}>禁用</a>
          )}
          <a onClick={() => eidtItemOpera(record)}>修改</a>
          <a onClick={() => handleAcitons('delete', record)}>删除</a>
        </div>
      ),
    },
  ];

  return (
    <PageTable
      total={total}
      pageTitle="项目管理"
      uniqueKey="id"
      tableList={tableList}
      getTableList={getTableList}
      columns={columns}
      filters={filterCfgList}
      showCreate={true}
      createTitle="新增项目"
      createCallback={createItemOpera}
      needRefresh={needRefresh}
    >
      <CommonModal
        onCancel={hideModal}
        visible={modalStatus === ModalStatus.Delete}
        title={MODAL_CFG[operaType].title}
        onOk={MODAL_CFG[operaType].onOk}
      >
        <div>{MODAL_CFG[operaType].content}</div>
      </CommonModal>

      <DepartmentModal
        status={modalStatus}
        hideModal={hideModal}
        selectedItem={itemInfo}
        createItem={createItem}
        updateItem={updateItem}
        filterOpts={filterOpts}
        loading={createLoading}
        setItemInfo={setItemInfo}
      />
    </PageTable>
  );
};

const mapStateToProps = ({ manageDepartment, loading }: ConnectState) => {
  return { manageDepartment, createLoading: loading.effects['manageDepartment/createItem'] };
};

const mapDispatchToProps = (dispatch: Dispatch) => {
  const namespace = 'manageDepartment';

  return {
    getTableList: (params: IDepartmentListQueryParams) =>
      dispatch({ type: `${namespace}/queryTableList`, payload: params }),
    getFilters: () => dispatch({ type: `${namespace}/queryFilterOpts` }),
    createItem: (params: IDepartmentListQueryParams) =>
      dispatch({ type: `${namespace}/createItem`, payload: params }),
    deleteItem: (id: number) => dispatch({ type: `${namespace}/deleteItem`, payload: id }),
    updateItem: (params: IDepartmentListQueryParams) =>
      dispatch({ type: `${namespace}/updateItem`, payload: params }),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(ManageDepartment);
